package com.mima.minaserver.client;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mima.minaserver.service.AliCloudMessage;

public class AliClient {
	private static Logger logger = LoggerFactory.getLogger(AliCloudMessage.class);

	/**
	 * 向阿里发送信息
	 * 
	 * @param url
	 * @param json
	 * @param encoding
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static int sendPostDataByJson(String url, String uuid, String account, String password, String secret_key,Integer key_id) {
		logger.info("{UUID=" + uuid + ",URL=" + url + ",ACCOUNT=" + account + ",PASSWORD=" + password + ",SECRET_KEY="
				+ secret_key + ",KEY_ID=" + key_id + "}");
		CloseableHttpClient httpclient = null;
		CloseableHttpResponse h_response = null;
		try {
			httpclient = HttpClients.createDefault();
			HttpPost http = new HttpPost(url);
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			nvps.add(new BasicNameValuePair("uuid", uuid));
			nvps.add(new BasicNameValuePair("account", account));
			nvps.add(new BasicNameValuePair("password", password));
			nvps.add(new BasicNameValuePair("secret_key", secret_key));
			nvps.add(new BasicNameValuePair("key_id", key_id.toString()));
			http.setEntity(new UrlEncodedFormEntity(nvps));
			h_response = httpclient.execute(http);
			logger.info("{h_response StatusCode="+h_response.getStatusLine().getStatusCode()+"}");
			return h_response.getStatusLine().getStatusCode();
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("{h_response StatusCode="+HttpStatus.SC_INTERNAL_SERVER_ERROR+"}");
			return HttpStatus.SC_INTERNAL_SERVER_ERROR;
		} finally {
			if (httpclient != null) {
				try {
					httpclient.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (h_response != null) {
				try {
					h_response.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
}